﻿using System.Collections;
using System.Collections.Generic;
using System.Linq.Expressions;
using DG.Tweening;
using UnityEngine;

//该脚本的作用在于控制目标物体的移动操作和生成球体
public class MoveManager : MonoBehaviour {
    public GameObject player;//获取目标物体
    public float speed = 5;//移动速度
    public float createTime;//生成球体的时刻
    public Vector3 mousePos;//当前鼠标位置
    public Vector3 initPos;//鼠标从屏幕坐标转换为世界坐标
    public float force = 700;//发射球体施加的力
    public int index;//生成球体的数量索引
    public float fireSpeed;//发射球体的速度
    Vector3 tar = new Vector3(0, 0, 0);
    // Start is called before the first frame update
    void Start() {
        //初始化
        Init();
    }

    //初始化数值
    void Init() {
        fireSpeed = 7;
        initPos = new Vector3(0, 0, -fireSpeed);
        speed = 5;
        player = GameObject.Find("Player");
        force = 700;
        index = 0;
    }
    // Update is called once per frame
    void Update() {
        //控制玩家的移动
        player.transform.Translate(new Vector3(Input.GetAxis("Horizontal") * Time.deltaTime * speed, 0, Input.GetAxis("Vertical") * Time.deltaTime * speed));
        Vector3 screenPos = Camera.main.WorldToScreenPoint(initPos); //将目标的世界坐标转换成屏幕坐标
        Vector3 mousePos = Input.mousePosition;
        mousePos.z = screenPos.z; // 这个很关键,鼠标的坐标投影到屏幕上
        Vector3 worldPos = Camera.main.ScreenToWorldPoint(mousePos);
        initPos = worldPos;
        //Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);//将屏幕坐标转换成射线
        //射线的起始点为相机的位置,方向为相机的位置指向由鼠标的世界坐标
        Ray ray = new Ray(Camera.main.transform.position, Camera.main.transform.position - initPos);
        Debug.DrawRay(ray.origin, ray.direction * 1000, Color.green);//绘制朝向的射线
        Camera.main.transform.position=transform.position;//相机的位置随着玩家的位置更新

        if (Input.GetMouseButtonDown(0)) {
            GameObject temp = Instantiate((GameObject)Resources.Load("Prefabs/Sphere"));//加载预制体资源
            temp.transform.position = player.transform.position;//球体的位置置为当前玩家的位置
            temp.name = "Sphere" + index;//球体的名称为迭代加1
            index++;
            temp.GetComponent<Rigidbody>().AddForce(ray.direction * 5 * force);//施加力
            //Debug.Log(ray.direction);
        }
        if (Input.GetMouseButtonDown(1)) {
            //Debug.Log("右键");
            tar = new Vector3(ray.direction.x, 0, ray.direction.z);//鼠标右键Down下,更新目标朝向
        }
        //插值目标的朝向和目标朝向(缓动效果)
        player.transform.forward = Vector3.Slerp(player.transform.forward, tar, 0.2f);
    }

}